import hashlib
import tempfile
import os
import unittest


def generate_md5(file_path):
    # 创建一个MD5哈希对象
    md5_hash = hashlib.md5()

    # 以二进制模式读取文件，并逐块更新哈希值
    with open(file_path, 'rb') as file:
        for chunk in iter(lambda: file.read(4096), b""):
            md5_hash.update(chunk)

    # 返回文件的MD5哈希值
    return md5_hash.hexdigest().encode('utf-8')


class TestGenerateMD5(unittest.TestCase):
    def setUp(self):
        # 创建一个临时文件用于测试
        self.test_content = b"Hello, this is a test file content for MD5 hashing."
        self.expected_md5 = hashlib.md5(self.test_content).hexdigest().encode('utf-8')

        # 创建临时文件并写入内容
        with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
            tmpfile.write(self.test_content)
            self.test_file_path = tmpfile.name

    def tearDown(self):
        # 删除临时文件
        os.remove(self.test_file_path)

    def test_generate_md5_correctness(self):
        # 测试生成的MD5是否正确
        computed_md5 = generate_md5(self.test_file_path)
        self.assertEqual(computed_md5, self.expected_md5, "MD5 hash should match expected value")

    def test_generate_md5_non_empty(self):
        # 确保返回的MD5不为空
        computed_md5 = generate_md5(self.test_file_path)
        self.assertTrue(len(computed_md5) > 0, "MD5 hash should not be empty")


if __name__ == '__main__':
    unittest.main()
